package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    // 微信服务接口地址
    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String APPID = "appid";
    private static final String SECRET = "secret";
    private static final String JS_CODE = "js_code";
    private static final String GRANT_TYPE = "grant_type";
    private static final String GRANT_TYPE_VALUE = "authorization_code";

    private static final String OPENID = "openid";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        String js_code = userLoginDTO.getCode();
        String openId = getOpenId(js_code);

        // 判断openId是否为空，如果为空表示登录失败，抛出业务异常
        if (openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 判断用户是否注册
        User user = userMapper.getUserByOpneId(openId);

        if(user == null){
            user = User.builder()
                        .openid(openId)
                        .createTime(LocalDateTime.now())
                        .build();
            userMapper.addUser(user);
            user.setId(user.getId());
        }
        return user;
    }

    private String getOpenId(String js_code) {
        Map<String, String> map = new HashMap<>();

        // 定义请求体
        map.put(APPID, weChatProperties.getAppid());
        map.put(SECRET, weChatProperties.getSecret());
        map.put(JS_CODE, js_code);
        map.put(GRANT_TYPE, GRANT_TYPE_VALUE);

        //调用微信接口服务，获取微信用户唯一标识
        String json = HttpClientUtil.doGet(URL, map);
        JSONObject jsonObject = JSON.parseObject(json);

        return jsonObject.getString(OPENID);
    }
}
